package JDBC;
import Utils.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * 使用PreparedStatement执行sql对象
 * 练习：
 *  * 1.通过键盘录入用户名和密码
 *  * 2.判断用户是否登录成功
 *  * 账户：zhangs   密码：123
 *
 * 注：配置目录下的properties文件
 *
 * @author Mc.Chai
 * @program: JavaWeb
 * @create 2021-12-15-17:10 17:10
 */
public class JDBCPreparedStatement {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("请输入用户名：");
        String username = input.nextLine();
        System.out.println("请输入密码：");
        String password = input.nextLine();
        if( new JDBCPreparedStatement().login(username,password) ){
            System.out.println("登录成功！");
        }else{
            System.out.println("登录失败！");
        }

    }
    public boolean login(String username,String password){
        Connection connection=null;
        PreparedStatement preparedStatement=null;
        ResultSet resultSet=null;
        if (username==null||password==null) {return false;}
        try {
            connection = JDBCUtils.getConnection();
            String sql="select * from user where username=? and userpwd=?";
            //获取preparedStatement对象
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1,username);
            preparedStatement.setString(2,password);
            resultSet = preparedStatement.executeQuery();
            if(resultSet.next()){
                System.out.println("登录成功");
                return true;
            }else{
                System.out.println("登录失败");
                return false;
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            JDBCUtils.close(resultSet,preparedStatement,connection);
        }
        return false;
    }
}
